//microcommand define fim*
inject(["cache"])

function cache(session, args, options, messageId = session.messageId) {
  ctx.cache.set(
    `microcommands:fim*.context`,
    `${session.platform}:${session.channelId}:${messageId}`,
    { args, options },
    Time.week,
  ).catch(e => ctx.logger.error(e))
}

ctx.before("command/execute", ({ session, command, args, options, root }) => {
  if (root && command.name === "fim" && session?.messageId) cache(session, args, options)
})

signature("", { captureQuote: false })
option("multiline", "-m", { descPath: "commands.fim.options.multiline" })
option("multiline", "-M, --no-multiline", { value: false, descPath: "commands.fim.options.multiline.false" })
option("temperature", "-t <0~2:number>", { descPath: "commands.fim.options.temperature" })
option("print", "-p")
action(async ({ session, options, root }) => {
  if (!session.quote) return session.i18n(".expect-quote")
  const messageId = session.quote.quote?.id
  if (!messageId) return void session.send(session.i18n(".context-not-found"))

  const context = await ctx.cache.get(
    `microcommands:fim*.context`,
    `${session.platform}:${session.channelId}:${messageId}`,
  )
  if (!context) return void session.send(session.i18n(".context-not-found"))

  let arg = context.args[0] || ""
  arg += h("", session.quote.elements).toString(true)
  if (context.args.length > 1) arg += context.args[1]
  options = { ...context.options, ...options }

  if (options.print) return arg

  cache(session, [arg], options, session.quote.id)
  const result = await session.execute({
    name: "fim",
    args: [arg],
    options,
  }, true)
  if (root && session.quote.id) result.unshift(h.quote(session.quote.id))
  return result
})

locale("zh-CN", {
  description: "继续使用 fim 指令续写文本",
  usage: "调用时，请引用上一条 fim 指令的结果。指令会自动继承之前 fim 指令的选项，您也可以传入选项来覆盖原来的设置。",
  messages: {
    "expect-quote": "缺少消息引用…",
    "context-not-found": "未找到对应的 fim 指令调用…",
  },
  options: {
    print: "返回目前为止的全文，而非继续调用 fim 指令",
  },
})